package com.binge.test4;

import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.Test;

import java.util.Arrays;
import java.util.Properties;
import java.util.Scanner;

/**
 * ClassName:KafkaProducerTest
 * Package:com.binge.test4
 * Description:
 *
 * @Author @Bin
 * @Date 2023/11/15-15:40
 * @Version: v1.0
 */
public class KafkaProducerTest {


    @Test
    public void testKafkaProducer() {
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "101.42.54.46:9092");
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
        ProducerRecord<String, String> producerRecord = new ProducerRecord<>("test", "test", "test");
        kafkaProducer.send(producerRecord, (metadata, exception) -> {
            if (exception != null) {
                exception.printStackTrace();
            }
            System.out.println(metadata);
        });

        Scanner scanner = new Scanner(System.in);
        scanner.next();
    }


    @Test
    public void testKafkaConsumer() {
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "101.42.54.46:9092");
        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("group.id", "abc");


        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
        kafkaConsumer.subscribe(Arrays.asList("test"));

        while (true) {
            ConsumerRecords<String, String> poll = kafkaConsumer.poll(1000);
            poll.forEach(record -> {
                System.out.println("record: " + record);
            });
        }
    }
}
